﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Components;
using Controls;
using UI.Lib;
using UI.Lib.Factory;

namespace UI.BuyManagement
{
    public partial class FrmAcceptMedit : UI.ParentForm.BaseMedit
    {
        public FrmAcceptMedit(string modulecode, string action, string text, string key)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.Text = text;
            this.Key = key;

            //回写的方法
            this.SaveCallFuntion = "Buy3a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            base.MaxStateFlag = true;
            this.allowDtlEmpty = false; //可能用户一次想把全部的记录删除
            if (!string.IsNullOrEmpty(this.Key))
            {
                LoadData();
                IsAfterSaveCloseWin = true;
            }

            tspBtnAdd.Visible = false;
            tspBtnDel.Visible = false;

            if ("P" == action)
            {
                this.saveDtlDataToServer = false;
                this.tspTop.Items[0].Visible = false;

                //收货单录入的功能按钮
                this.tspTop.Items.Insert(0, this.CreateToolBtn("P", "打印", new EventHandler(delegate
                {
                    MessageBox.Show("打印");
                })));
            }
        }

        protected override void PageInit()
        {
            this.tbSummary.DefaultWidth = 120;
        }

        private bool? _hasCanModifyDocnoRight;
        private bool HasCanModifyDocnoRight
        {
            get
            {
                if (_hasCanModifyDocnoRight == null)
                {
                    var hsWhere = new Hashtable();
                    hsWhere["modulecode"] = this.ModuleCode;
                    hsWhere["actioncode"] = "N"; //是否有修改退货单的权限
                    hsWhere["usercode"] = Context.User.Uesrcode;

                    //查询数据库是否拥有重新打印的权限
                    DataTable dt = CommonHelper.Entity.ExecFun("checkRight", hsWhere);

                    _hasCanModifyDocnoRight = (null != dt && 0 != dt.Rows.Count);
                }


                return _hasCanModifyDocnoRight != null && _hasCanModifyDocnoRight.Value;
            }
        }

        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.listid ='{0}' ", this.Key));
            base.LoadDtlData(null, string.Format(" a.plistid ='{0}' ", this.Key));

            if ("W" == this.Action)
            {
                //让第一行的实收数量得到焦点
                this.dgvDtl.Focus(0, "dtlqty");

                SetDefaultValue();
            }
        }

        protected override void AfterSystemChangeControlState()
        {
            base.AfterSystemChangeControlState();

            if ("W" == this.Action)
            {
                var hasRight = HasCanModifyDocnoRight;
                if (!hasRight)
                {
                    this.tbSummary.Enable("arrno", false);
                }
            }
        }

        protected override void AfterCreateSummaryControl(string name, Control c)
        {
            if ("arrno" == name) //验证销售单号是否存在
            {
                var txtAcceptDocno = c as TextBoxX;
                if (txtAcceptDocno != null)
                    txtAcceptDocno.ValueChanged += TxtSellDocnoValueChanged;
            }
        }

        private void TxtSellDocnoValueChanged(object sender, EventArgs e)
        {
            //连接数据库，验证存在性
            if (("W" == this.Action) && this.isLoadOk)
            {
                string sendocno = Validation.ToString(this.tbSummary.GetValue("arrno"));
                if (string.IsNullOrEmpty(sendocno)) return;

                var hs = new Hashtable();
                hs["listid"] = this.tbSummary.GetValue("listid");
                hs["muser"] = Context.Comocde;
                hs["docno"] = sendocno;
                string reflt = CommonHelper.Entity.ExecFunScalar("checkacceptdocno", hs);
                if (!string.IsNullOrEmpty(reflt))
                {
                    MessageBox.Show("当前输入的收货单号重复，请重新录入！", "提示");
                    this.tbSummary.ClearItem("arrno");
                    // else ((TextBoxX)sender).Revocation(); //重置
                }
            }
        }

        protected override void AfterGridEndEdit(string colName, DataGridViewCellEventArgs e)
        {
            if ("accqty" == colName) //实收数量改变时计算税额和收货金额
            {
                double price = Validation.ToDouble(this.dgvDtl.GetValue("bprice")); //进价
                double accqty = Validation.ToDouble(this.dgvDtl.GetValue("accqty")); //收货数量
                double all = price * accqty; //还要算上税率

                this.dgvDtl.SetValue("accamt", all);
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("accamt" == name) //明细行的收货金额改变后，计算所有明细行的收货金额之和
            {
                this.tbSummary.SetValue("accamt", CalcDtlAmt());

                //本行的收货金额改变时，计算税额
                double accamt = Validation.ToDouble(this.dgvDtl.GetValue("accamt")); //收货金额
                double cess = Validation.ToDouble(this.dgvDtl.GetValue("cess")); //税额

                this.dgvDtl.SetValue("cessamt", Validation.ToDouble(accamt * cess, 3));
            }
            else if ("dtlqty" == name)
            {
                var sendQty = Validation.ToFloat(this.dgvDtl.GetValue("dtlqty"));
                var cess = Validation.ToFloat(this.dgvDtl.GetValue("cess"));
                var price = Validation.ToFloat(this.dgvDtl.GetValue("price"));
                var amt = sendQty * price;

                this.dgvDtl.SetValue("dtltotalamt", Math.Round(amt + amt * cess, 3));
            }
        }

        private double CalcDtlAmt()
        {
            double sum = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sum += Validation.ToDouble(dr.Cells["accamt"].Value);
            }

            return sum;
        }

        /// <summary>
        /// 设置默认值
        /// </summary>
        private void SetDefaultValue()
        {
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                if ("W" == this.Action)
                {
                    dr.Cells["dtlqty"].Value = 0;
                    dr.Cells["actqty2"].Value = 0;
                    dr.Cells["dtltotalamt"].Value = 0;
                }
            }
        }
    }
}
